import json
import threading
import time

from odoo import models
from ...functions.marketing_reward_schedule_func import MarketingRewardScheduleFunc
from multiprocessing import Queue


class RpRegisterMockTranInheritForMarketing(models.TransientModel):
    _inherit = 'rp.register'
    _description = '注册'

    q = Queue()  # 监听注册消息的队列
    lock = threading.Lock()  # 锁

    def generator_invite_register_task(self):
        """生成注册邀请码"""
        self.ensure_one()
        registered_person = self.env['rp.customer'].search([])
        for person in registered_person:
            category = self.env['rp.invite.category'].search([('name', '=', '注册')])
            MarketingRewardScheduleFunc(self.env).generator_invite_task(category, person)

    def register_customer(self):
        self.ensure_one()
        res_person = super(RpRegisterMockTranInheritForMarketing, self).register_customer()
        # 推送消息到队列（充分解耦）
        payload = json.dumps({'id': res_person.id, 'invite_code': self.invite_code})
        RpRegisterMockTranInheritForMarketing.q.put(payload)
        # 填写邀请码时的奖励（返余额，或返现）
        if self.invite_code:
            # 搜寻注册类型ID
            category_id = self.env['rp.invite.category'].search([('name', '=', '注册')])
            person = self.env['rp.customer'].browse(res_person.id)
            MarketingRewardScheduleFunc(self.env).gain_reward_related_invite(self.invite_code, category_id, person)
